package com.example.smartcs.service.impl;

import com.example.smartcs.model.ChatMessage;
import com.example.smartcs.service.SessionService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.stream.Collectors;

@Slf4j
@Service
public class SessionServiceImpl implements SessionService {

    // 会话ID -> 消息列表
    private final Map<String, List<ChatMessage>> sessions = new ConcurrentHashMap<>();

    @Override
    public String createNewSession() {
        String sessionId = UUID.randomUUID().toString();
        sessions.put(sessionId, new ArrayList<>());
        log.info("创建新会话: {}", sessionId);
        return sessionId;
    }

    @Override
    public List<String> getAllSessionIds() {
        return new ArrayList<>(sessions.keySet());
    }

    @Override
    public List<ChatMessage> getSessionMessages(String sessionId) {
        List<ChatMessage> messages = sessions.getOrDefault(sessionId, Collections.emptyList());
        // 按时间戳排序
        return messages.stream()
                .sorted(Comparator.comparing(ChatMessage::getTimestamp))
                .collect(Collectors.toList());
    }

    @Override
    public void addMessageToSession(ChatMessage message) {
        String sessionId = message.getSessionId();
        if (sessionId == null || sessionId.isEmpty()) {
            log.warn("尝试添加消息到空会话ID");
            return;
        }
        
        // 如果会话不存在，则创建
        sessions.computeIfAbsent(sessionId, k -> new ArrayList<>());
        
        // 设置消息ID和时间戳
        if (message.getId() == null || message.getId().isEmpty()) {
            message.setId(UUID.randomUUID().toString());
        }
        
        if (message.getTimestamp() == null) {
            message.setTimestamp(LocalDateTime.now());
        }
        
        // 添加消息
        sessions.get(sessionId).add(message);
        log.debug("添加消息到会话 {}: {}", sessionId, message.getContent());
    }

    @Override
    public void deleteSession(String sessionId) {
        sessions.remove(sessionId);
        log.info("删除会话: {}", sessionId);
    }

    @Override
    public void clearAllSessions() {
        sessions.clear();
        log.info("清空所有会话");
    }
} 